<template>
  <div class="city-region-selector">
    <!-- 使用下拉菜单+复选框组实现下拉复选 -->
    <el-dropdown placement="bottom-start" v-if="cityOptions?.children?.length > 0">
      <el-checkbox :indeterminate="indeterminate" v-model="checkAll"
        :disabled="cityCode.length == 0 && cityOptions.isOwn != 2" @click="handleExhibitionClick(cityOptions)"
        @change="handleCheckAllChange"> {{ cityOptions.name }} {{ selectedCity.length == 0 ? '' : selectedCity.length }}
      </el-checkbox>


      <!-- 修复条件判断：检查cityOptions数组长度而非children -->
      <span class="select-trigger" v-if="cityOptions?.children?.length > 0">
        {{ selectedCity.length > 0 ? cityOptions.name : cityOptions.name + selectedCity.length }}
        <el-icon class="el-icon--right">
          <ArrowDown />
        </el-icon>
      </span>

      <!-- 恢复下拉菜单内容 -->
      <template #dropdown>
        <div class="checkbox-group-container">
          <el-checkbox-group v-model="selectedCity" @change="handleCityChange">
            <el-checkbox v-for="city in cityOptions.children" :key="city.code"
              :disabled="cityCode.length == 0 && city.isOwn != 2" @click="handleExhibitionClick(city)" :label="city.name">
              {{ city.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
    </el-dropdown>
    <div v-else>
      <el-checkbox :label="cityOptions.code" :disabled="cityCode.length == 0 && cityOptions.isOwn != 2"
        @change="handleCityChange">


        {{ cityOptions.name }}
      </el-checkbox>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { ArrowDown } from '@element-plus/icons-vue';

const checkAll = ref(false);
const indeterminate = ref(false);
const props = defineProps({
  cityOptions: {
    type: Object,
    required: true,
    default: () => ({})
  },
  cityCode: {
    type: String,
    default: ''
  },

  onChildData: {
    type: Function as () => (data: { index: string; list: string[] }) => void,
    default: () => (data: { index: string; list: string[] }) => { }
  }
});

const emit = defineEmits(['update:modelValue']);
const selectedCity = ref<string[]>([]); // 明确类型为字符串数组
// 新增：收集所有lockFlag为0的code（包括嵌套children）
const allUnlockedCodes = ref<string[]>([]);

const collectUnlockedCodes = (options: any): string[] => {
  const codes: string[] = [];
  console.log('newCityCode=====', props.cityCode)

  // 当前节点lockFlag为0时收集code
  if (options.isOwn === 2 && props.cityCode.length == 0) {
    codes.push(options.code);
  }
  // 递归处理子节点
  if (options.children && Array.isArray(options.children)) {
    options.children.forEach((child: any) => {
      if (child.isOwn === 2 && props.cityCode.length == 0) {
        codes.push(...collectUnlockedCodes(child));
      }
    });
  }
  console.log('codes===============', codes);

  return codes;
};

// 初始化时执行收集
selectedCity.value = collectUnlockedCodes(props.cityOptions);
// 全选/取消全选逻辑
const handleCheckAllChange = (val: boolean) => {

  const eligibleCities = props.cityOptions.children?.filter((city: { isOwn: number; }) =>
    props.cityCode.length === 0 ? city.isOwn === 2 : true
  ) || [];
  const allCityNames = eligibleCities.map((city: { name: any; }) => city.name);
  selectedCity.value = val ? allCityNames : [];
  props.onChildData({ index: props.cityOptions.code, list: selectedCity.value });
};

// 子复选框变化时更新全选状态
const handleCityChange = (value: string[]) => {
  props.onChildData({
    index: props.cityOptions.code,
    list: value || []
  });
};
const handleExhibitionClick = (city: any) => {
  if (props.cityCode.length == 0 && city.isOwn != 2) {
    //通知组件弹窗
    props.onChildData({ index: -1, list: city });

  }
}

//监听选中值变化，更新全选和半选状态
watch(selectedCity, (newVal) => {
  const allCityNames = props.cityOptions.children?.map(city => city.name) || [];
  const total = allCityNames.length;
  const checkedCount = newVal.length;

  checkAll.value = checkedCount === total && total > 0;
  indeterminate.value = checkedCount > 0 && checkedCount < total;
}
);
// 添加对cityCode的监听
watch(
  () => props.cityCode,
  (newCityCode, oldCityCode) => {
    // 当cityCode变化时执行的逻辑
    console.log('cityCode changed:=====', newCityCode, selectedCity.value);

    // 可以在这里添加需要的处理逻辑，例如重置选中状态等
    if (newCityCode) {
      console.log('newCityCode=====',selectedCity.value)

      // 根据新的cityCode执行相应操作
      selectedCity.value = [];
    }
  }
);

</script>

<style scoped lang="less">
/* 可以根据需要添加组件样式 */
.city-region-selector {
  min-width: 94px;
  /* 设置最小宽度 */
  padding-right: 15px;
  height: 28px;
}

.filter-content {}

.city-region-selector__label {
  background: url('@/assets/images/suo.png') no-repeat;
  padding-left: 20px;
}

/* 添加下拉菜单容器样式 */
.checkbox-group-container {
  padding: 10px;
  width: 110px;
  max-height: 200px;
  overflow-y: auto;
}

::v-deep .el-checkbox.is-disabled {

  /* 禁用状态下的文本颜色 */
  .el-checkbox__label {
    color: #909399;
    line-height: 20px;
    /* 调整为较深的灰色，默认是 #c0c4cc */
  }

  /* 禁用状态下的复选框样式 */
  .el-checkbox__input.is-disabled .el-checkbox__inner {
    border-color: #fff;
    /* 边框颜色 */
    height: 18px;
    cursor: pointer;
    /* 调整锁图标大小 */
    background-position: center;
    /* 图标居中 */
    background: url('@/assets/images/suo.png') no-repeat;
    /* 鼠标悬停显示小手 */
    background-size: 11px auto;
    padding-left: 10px;
    /* 背景色 */
  }
}

.el-checkbox {
  display: block;
  margin-bottom: 8px;
}
</style>
